const { Nuxt, Builder } = require('nuxt')
const bodyParser = require('body-parser')
const session = require('cookie-session')
const app = require('express')()
const proxy = require('express-http-proxy')

// Body parser，用来封装 req.body
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: true }));

// Sessions 来创建 req.session
app.use(session({
  secret: 'super-secret-key',
  resave: false,
  saveUninitialized: false,
  cookie: { maxAge: 10*60*60*1000 } //10小时
}))

let proxyRoute = proxy('http://localhost:8000',{
  proxyReqPathResolver: function(req) {
      return require('url').parse(req.url).path;
  },
  userResDecorator: function(proxyRes, proxyResData, req, res) {
    data = JSON.parse(proxyResData);    
    let reqUrl = req.url
    if(data.status==1){
      if(reqUrl.indexOf('/login')>-1){
        req.session.userInfo = data.result.user
      }else{
        delete req.session.userInfo        
      }
    }
    return JSON.stringify(data);
  }  
})

//app.get('/proxy/', proxyRoute)

app.use("/proxy",proxyRoute)

// 发起 POST /api/logout 请求注销当前用户，并从 req.session 中移除
// app.get('/proxy/auth/logout', function (req, res) {
//   delete req.session.userInfo
//   res.json({ ok: true })
// })

// 我们用这些选项初始化 Nuxt.js：
const isProd = process.env.NODE_ENV === 'production'
let config = require('./nuxt.config')
config.dev = !isProd
const nuxt = new Nuxt(config)
// 生产模式不需要 build
if (!isProd) {
  const builder = new Builder(nuxt)
  builder.build()
}
app.use(nuxt.render)
app.listen(3000)
console.log('Server is listening on http://localhost:3000')